# -*- coding: utf-8 -*-


import os
import logging
import ConfigParser

from PyQt4 import QtCore, QtGui

CODEC = 'utf-8'

SONGS_FORMARTS = ('mp3', 'wav', 'waf', 'rm', 'midi', 'cd', 'wma', 'ape', 'vqf', 'real', 'module', 'asf')


def songs_formats_2_str(fmt1, fmt2):
    if len(fmt1) <= 3:
        return fmt1.upper() + ' File' + '(*.' + fmt1 + ')' + '\n' + fmt2.upper() + ' File' + '(*.' + fmt2 + ')'
    return fmt1 + '\n' + fmt2.upper() + ' File' + '(*.' + fmt2 + ')'

FILTER_FORMAT_STR = reduce(songs_formats_2_str, SONGS_FORMARTS)


class SongManager(object):
    """歌曲列表管理类"""

    SEC_PLAYER = "Player"
    SEC_PLAYLIST = "PlayList"
    OPT_PATH = "path"
    OPT_LIST = "list"

    def __init__(self, file_url):
        self._list = []
        self._list_url = file_url

    def loadList(self):
        """根据地址获取文件初始化列表"""
        if not os.path.exists(self._list_url):
            logging.error('file_url 不存在')
            return
        cf = ConfigParser.ConfigParser()
        cf.read(self._list_url)
        path = cf.get(SongManager.SEC_PLAYER, SongManager.OPT_PATH)
        list = cf.get(SongManager.SEC_PLAYLIST, SongManager.OPT_LIST)
        self._list = eval(list)
        return path

    def saveList(self, path):
        """保存列表至文件"""
        with open(self._list_url, 'w') as f:
            cf = ConfigParser.ConfigParser()
            cf.add_section(SongManager.SEC_PLAYER)
            cf.add_section(SongManager.SEC_PLAYLIST)
            cf.set(SongManager.SEC_PLAYER, SongManager.OPT_PATH, path)
            cf.set(SongManager.SEC_PLAYLIST, SongManager.OPT_LIST, self._list)
            cf.write(f)

    def addSong(self, file_url, path):
        """添加歌曲(判断是否.mp3等格式,并判断歌曲是否已经存在)"""
        song_formate = file_url.split('.')[-1]
        try:
            SONGS_FORMARTS.index(song_formate.__str__())
        except ValueError:
            QtGui.QMessageBox.information(None, u"提示", u"文件格式不对!")
            return False
        finally:
            pass
        file_url_encode = file_url.__str__().encode(CODEC)
        if file_url_encode in self._list:
            logging.error('%s 歌曲已经存在，不能重复添加', file_url_encode)
            return False
        self._list.append(file_url_encode)
        self.saveList(path)
        return True

    def delSong(self, index, path):
        """删除歌曲"""
        self._list.remove(self._list[index])
        self.saveList(path)

    def getSong(self, index):
        """根据选取位置获取相应歌曲"""
        return self._list[index]

    @property
    def songCount(self):
        """返回列表的歌曲数量"""
        return len(self._list)

    @staticmethod
    def getSongName(song_url):
        """获取歌词名称"""
        name_with_suffix = os.path.split(song_url)
        return QtCore.QString.fromUtf8(name_with_suffix[1].split('.')[0])

    @staticmethod
    def getSongIrc(song_url):
        """获取歌词"""
        name_with_url = QtCore.QString(os.path.splitext(song_url)[0])
        name_with_url = name_with_url.replace('songs', 'lyrics')
        return QtCore.QString(name_with_url + '.lrc')
